package com.easylinkin.linkappapi.gaodemap.util;

import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.gaodemap.entity.GeoFence;
import com.easylinkin.linkappapi.gaodemap.entity.GeoFenceApiResult;
import com.easylinkin.linkappapi.openapi.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @program: linkapp-group
 * @description: 电子围栏
 * @author: chenkaixuan
 * @create: 2021-07-23 16:34
 */
@Slf4j
public class GeoFenceUtil {

    public static String getServiceId(GeoFence geoFence) throws Exception {
        String url="https://tsapi.amap.com/v1/track/service/add";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("name",geoFence.getName()));
        String result = sendPostRequest(url,list,geoFence.getKey());
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult.getData().getSid();
    }

    /***
     * 创建修改圆形围栏
     * @param geoFence
     * @return
     * @throws Exception
     */
    public static GeoFenceApiResult addOrUpdateCircle(GeoFence geoFence) throws Exception {
        Assert.notNull(geoFence,"参数不能为空");
        String modular="add";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if(!StringUtils.isEmpty(geoFence.getGfid())){
            modular="update";
            list.add(new BasicNameValuePair("gfid",geoFence.getGfid()));
        }
        String url=geoFence.getUrl()+"/"+modular+"/circle";
        addPublicParamMap(list,geoFence);
        list.add(new BasicNameValuePair("center",geoFence.getCenter()));
        list.add(new BasicNameValuePair("radius",String.valueOf(geoFence.getRadius())));
        String result = sendPostRequest(url, list,geoFence.getKey());
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult;
    }

    /***
     * 创建修改多边形围栏
     * @param geoFence
     * @return
     * @throws Exception
     */
    public static GeoFenceApiResult addOrUpdatePolygon(GeoFence geoFence) throws Exception {
        Assert.notNull(geoFence,"参数不能为空");
        String modular="add";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if(!StringUtils.isEmpty(geoFence.getGfid())){
            modular="update";
            list.add(new BasicNameValuePair("gfid",geoFence.getGfid()));
        }
        String url=geoFence.getUrl()+"/"+modular+"/polygon";
        addPublicParamMap(list,geoFence);
        list.add(new BasicNameValuePair("points",geoFence.getPoints()));
        String result = sendPostRequest(url, list,geoFence.getKey());
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult;
    }

    /***
     * 删除围栏
     * @param geoFence
     * @return
     * @throws Exception
     */
    public static GeoFenceApiResult delete(GeoFence geoFence) throws Exception {
        Assert.notNull(geoFence,"参数不能为空");
        Assert.notEmpty(geoFence.getGfids(),"gfids 不能为空");
        String url=geoFence.getUrl()+"/delete";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("key",geoFence.getKey()));
        list.add(new BasicNameValuePair("sid",geoFence.getSid()));
        list.add(new BasicNameValuePair("gfids",String.join(",",geoFence.getGfids())));
        String result = sendPostRequest(url, list,geoFence.getKey());
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult;
    }

    /**
     * 查询围栏
     * @param geoFence
     * @return
     * @throws Exception
     */
    public static GeoFenceApiResult list(GeoFence geoFence) throws Exception {
        String url = geoFence.getUrl()+"/list?" + HttpClientUtil.asUrlParams(appendParams(geoFence));
        HttpGet httpGet = new HttpGet(url);
        String result = HttpClientUtil.doGet(httpGet);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult;
    }

    public static GeoFenceApiResult statusLocation(GeoFence geoFence) throws Exception {
        String url = geoFence.getUrl()+"/status/location?" + HttpClientUtil.asUrlParams(appendParamsTerminal(geoFence));
        HttpGet httpGet = new HttpGet(url);
        String result = HttpClientUtil.doGet(httpGet);
        if(StringUtils.isEmpty(result)){
            return null;
        }
        GeoFenceApiResult geoFenceApiResult = JSONObject.parseObject(result,GeoFenceApiResult.class);
        log.info(result);
        if(!parameterJudge(geoFenceApiResult)){
            return null;
        }
        return geoFenceApiResult;
    }

    public static void main(String[] args) throws Exception {
        GeoFence geoFence=new GeoFence();
        geoFence.setKey("71786760fd3f5fc14116f8b7f6ffcdb9");
        geoFence.setSid("384077");
        geoFence.setName("ceshi20210727093405");
        geoFence.setUrl("https://tsapi.amap.com/v1/track/geofence");
//        geoFence.setCenter("114.404057,30.475014");
//        geoFence.setRadius(101);
        //geoFence.setRepeat("Mon,Tues,Wed,Thur,Fri,Sat,Sun");
        //geoFence.setGid("a1b07b7a-ef07-40e5-8812-def67ae14acf");
         //String geofence = geofence(geoFence);
       // boolean geofence = deleteGeoFence(geoFence);
        //geoFence.setGfid("123414");
        //addOrUpdateCircle(geoFence);
        list(geoFence);
       // geoFence.setGfids(Arrays.asList("123469","124772"));
////        delete(geoFence);
//        geoFence.setPoints("114.403896,30.47511;114.404121,30.47517;114.404057,30.474967;114.403859,30.475041");
//        addOrUpdatePolygon(geoFence);
//        geoFence.setLocation("114.403977,30.475078");
//        statusLocation(geoFence);
    }


    /***
     * 添加公共参数
     * @param list
     * @param geoFence
     */
    private static void addPublicParamMap(List<NameValuePair> list,GeoFence geoFence){
        list.add(new BasicNameValuePair("key",geoFence.getKey()));
        list.add(new BasicNameValuePair("sid",geoFence.getSid()));
        list.add(new BasicNameValuePair("name",geoFence.getName()));
        list.add(new BasicNameValuePair("desc",geoFence.getDesc()));
    }

    /***
     * 发送post请求
     * @param uri
     * @param list
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String sendPostRequest(String uri,List<NameValuePair> list,String key) throws UnsupportedEncodingException {
        Assert.notNull(uri,"请求接口地址不能为空");
        HttpPost httpPost = new HttpPost(uri);
        UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
        httpPost.setEntity(entityParam);
        httpPost.addHeader("key",key);
        String result = HttpClientUtil.doPost(httpPost);
        return result;
    }

    /***
     * 返回值判断
     * @param geoFenceApiResult
     * @return
     * @throws Exception
     */
    private static boolean parameterJudge(GeoFenceApiResult geoFenceApiResult) throws Exception {
        String zero="10000";
        if(!zero.equals(String.valueOf(geoFenceApiResult.getErrcode()))){
            throw new Exception(geoFenceApiResult.getErrmsg()+":"+geoFenceApiResult.getErrdetail());
        }
        return true;
    }

    private static Map<String, Object> appendParams(GeoFence geoFence){
        Map<String, Object> parmMap = new HashMap<>();
        parmMap.put("key",geoFence.getKey());
        parmMap.put("sid",geoFence.getSid());
        if(geoFence.getOutputshape() == null){
            parmMap.put("outputshape","1");
        }else{
            parmMap.put("outputshape",geoFence.getOutputshape());
        }
        if(geoFence.getGfids() != null && geoFence.getGfids().size()>0){
            parmMap.put("gfids",String.join(",",geoFence.getGfids()));
        }

        return parmMap;
    }

    private static Map<String, Object> appendParamsTerminal(GeoFence geoFence){
        Map<String, Object> parmMap = new HashMap<>();
        parmMap.put("key",geoFence.getKey());
        parmMap.put("sid",geoFence.getSid());
        parmMap.put("location",geoFence.getLocation());
        if(geoFence.getGfids() != null && geoFence.getGfids().size()>0){
            parmMap.put("gfids",String.join(",",geoFence.getGfids()));
        }
        return parmMap;
    }
}
